//
//  AuctionDetailVC.swift
//  LeGou
//
//  Created by lxm on 2022/10/15.
//

import UIKit

class AuctionAutoDetailVC: ZMViewController {

    //MARK:--------------------属性--------------------
    var id : Int = 0
    
    var data = ZMUtil.fastNilBehavior(type: AuctionModels.AutoAutionDetail.self)
    
    var records = ZMUtil.fastNilBehavior(type: [AuctionModels.ConflateRecord].self)
    
    var payHelper = PayHelper()

    let timer = Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
    
    var currentVersion = 0

    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var scyj: UILabel!
            
    let nav = NavigationBarView()
    
    @IBOutlet weak var banner: SDCycleScrollView!
    
    @IBOutlet weak var state: UILabel!
    // 价格前面的label
    @IBOutlet weak var pricePreTitle: UILabel!
    
    @IBOutlet weak var price: UILabel!
    
    @IBOutlet weak var startTimeLabel: UILabel!
    // 商品名字
    @IBOutlet weak var goodsName: UILabel!
    // 参与人数
    @IBOutlet weak var join: UILabel!
    // 围观人数
    @IBOutlet weak var look: UILabel!
    // 已出价
    @IBOutlet weak var givePrice: UILabel!
    // 起拍价
    @IBOutlet weak var startPrice: UILabel!
    // 加价幅度
    @IBOutlet weak var addRatio: UILabel!
    // 保证金
    @IBOutlet weak var insurance: UILabel!
    // 竞拍时间
    @IBOutlet weak var jpTime: UILabel!
    
    @IBOutlet weak var content: UIView!
    
    @IBOutlet weak var detialH: NSLayoutConstraint!
    
    @IBOutlet weak var recrodContent: UIStackView!
    
    @IBOutlet weak var recordContainer: UIView!
    
    @IBOutlet weak var sureButton: UIButton!
    
    @IBOutlet weak var recordCount: UILabel!
    
    @IBOutlet weak var kefu: UIImageView!
    
    let loading = XMLoadingView()
    
    let web = WKWebView()
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loading.showInView(fatherView: view)
        getInfo()
        getBidRecord()
    }
    
    //MARK:--------------------UI--------------------
    func setUI() {
        title = ""
        hbd_barHidden = true
        view.addSubview(nav)
        nav.backButton.setImage(UIImage.init(named: "auciton_back"), for: .normal)
        nav.autoBack = true
        // web
        content.addSubview(web)
        web.scrollView.isScrollEnabled = false
        web.scrollView.rx.observe(CGSize.self, "contentSize").subscribe(onNext:{ [unowned self] resp in
            if let size = resp {
                let h = size.height
                if self.web.superview != nil {
                   self.detialH.constant = h
                }
            }
        }).disposed(by: disposeBag)
        web.frame = CGRect(x: 12, y: 12, width: SCREEN_W - 24, height: 10)
        web.layer.cornerRadius = 8
        web.layer.masksToBounds = true
    }
    
    func addConstraints() {
        nav.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        
        web.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            
        }
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        data.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            if let imgs = resp.productInfo.sliderImage.zm.toArray() {
                self.banner.imageURLStringsGroup = imgs
            }
            self.state.text = resp.desTitle()
            self.scyj.text = "今日成功合成：\(resp.dayConflateCount)次"
            self.scyj.isHidden = (resp.state == nil || resp.state == .signed)
            self.price.text = "\(resp.enrollCount)人"
            self.goodsName.text = resp.productInfo.storeName
            //            self.join.isHidden = resp.joinCount == 0
            self.join.text = "参与\(resp.joinCount)次"
            self.look.text = "获得 \(resp.giveCount) 件"
            self.givePrice.text = "合成 \(resp.conflateCount) 次"
            
            let start = AuctionService.shared.dateFromToday(.milliseconds(resp.startMillis))
            let end = AuctionService.shared.dateFromToday(.milliseconds(resp.endMillis))
            
            switch resp.state {
                case .signed: self.startTimeLabel.text = "今日 \(start.zm.toString("HH:mm")) 开始"
                case .process : self.startTimeLabel.text = "今日 \(end.zm.toString("HH:mm")) 结束"
                case .stop: self.startTimeLabel.text = "今日 \(end.zm.toString("HH:mm")) 结束"
                case .over:self.startTimeLabel.text = "明日 \(start.zm.toString("HH:mm")) 开始"
                case .none: self.startTimeLabel.text = "今日 \(start.zm.toString("HH:mm")) 开始"
            }
            
            self.jpTime.text = start.zm.toString("MM.dd HH:mm:ss") + "-" + end.zm.toString("MM.dd HH:mm:ss")
            self.startPrice.text = "¥" + resp.startPrice.zm.toString(keep: 2)
            self.addRatio.text = "¥" + resp.stepPrice.zm.toString(keep: 2)
            self.insurance.text = "¥" + resp.bail.zm.toString(keep: 2)
            
            
            self.web.loadHTMLString(resp.productInfo.content.zm.htmlBigSizeString(), baseURL: nil)
            self.setStyle(s: self.map(s: resp.state, interruptType: resp.interruptType))
        }).disposed(by: disposeBag)
        
        // 记录
        records.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            self.recrodContent.arrangedSubviews.forEach {[unowned self]  v in
                self.recrodContent.removeArrangedSubview(v)
            }
            for i in 0 ..< resp.count {
                let m = resp[i]
                let color = "#666666".zm.hex()
                let rv = AuctionDetailRecordView()
                rv.leftLabel.setTitle("\(m.showId)  \(m.cityName) \(m.conflateTime.zm.stringToString(toFormate: "MM.dd HH:mm:ss"))", for: .normal)
                rv.leftLabel.setTitleColor(color, for: .normal)
                rv.leftLabel.tintColor = color
                rv.rightLabel.text = "合成成功"
                rv.rightLabel.textColor = color
                self.recrodContent.addArrangedSubview(rv)
            }
            self.recordContainer.isHidden = resp.count == 0
        }).disposed(by: disposeBag)
        
        _ = kefu.zm.addTapGestureRecognizer(target: self, action: #selector(onKefu))
        
        _ = recordCount.zm.addTapGestureRecognizer(target: self, action: #selector(onRecord))
    }
    
    @objc func onKefu() {
        CommonService.shared.showContactService()
    }
    
    @objc func onRecord() {
        let vc = AutoCompoundRecord()
        vc.ahGoodsRecordId = id
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func getBidRecord() {
        AuctionAPI.getConflateRecord(["limit" : 5, "page" : 1, "productId" : id]).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            let total = JSON(resp)["total"].intValue
            if let list = resp["list"] as? [[String : Any]], let m = [AuctionModels.ConflateRecord].deserialize(from: list) {
                self.records.accept(m.compactMap({$0}))
            } else {
                self.records.accept([])
            }
            self.recordCount.text = "\(total)条"
        }).disposed(by: disposeBag)
    }
    
    func getInfo() {
        let pa = ["ahProductId" : id] as [String : Any]
        AuctionAPI.autoDetail(pa).rxRequest(type: AuctionModels.AutoAutionDetail.self).subscribe(onNext:{ [unowned self] resp in
            self.data.accept(resp)
            self.loading.hideView(anmation: true)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    @IBAction func onSign(_ sender: Any) {
        guard let data = data.value else {return}
        if data.state == nil || data.state == .stop {
            // 报名
            ZMAlertView.show(content: "确定要报名吗？", left: "取消", right: "确定", onLeft: nil) {
                self.sendSign()
            }
        }
    }
    
    @IBAction func onMyRecord(_ sender: Any) {
        let vc = MyCompoundRecrod()
        vc.ahGoodsRecordId = id
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // 报名
    func sendSign() {
        guard let data = data.value else {return}
        var requests = [Observable<Any?>]()
        if data.state == nil {
            requests.append(AuctionAPI.enroll(["ahProductIds" : "\(id)"]).rxRequestNullAble(type: Any.self))
        } else if data.state == .stop {
            requests.append(AuctionAPI.recoverAutoAuction(["ahProductIds" : "\(id)"]).rxRequestNullAble(type: Any.self))
        }
        ZMToast.showActivity()
        Observable.combineLatest(requests).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            self.getInfo();
        }).disposed(by: disposeBag)
    }
    
    func map(s : AuctionModels.AutoState?, interruptType : Int) -> Int {
        guard let s = s else {
            return -1
        }
        if s == .signed {
            return 0
        } else if s == .process {
            return 1
        } else if s == .stop {
            return interruptType == 0 ? 3 : 2
        } else if s == .over {
            return interruptType == 2 ? 5 : 4
        }
        return 0
    }
    
    func setStyle(s : Int) {
        if s == -1 {
            // 未报名
            sureButton.backgroundColor = Style.mainColor
            sureButton.layer.borderWidth = 0
            sureButton.setTitle("立即报名", for: .normal)
            sureButton.setTitleColor(.white, for: .normal)
        } else if s == 0 {
            // 已报名
            sureButton.backgroundColor = "#FCECE9".zm.hex()
            sureButton.layer.borderWidth = 0
            sureButton.setTitle("已报名", for: .normal)
            sureButton.setTitleColor(Style.mainColor, for: .normal)
        } else if s == 1 {
            // 竞购中
            sureButton.backgroundColor = "#FCECE9".zm.hex()
            sureButton.layer.borderWidth = 0
            sureButton.setTitle("自动竞购中...", for: .normal)
            sureButton.setTitleColor(Style.mainColor, for: .normal)
        } else if s == 2 {
            // 竞购中断
            sureButton.backgroundColor = .white
            sureButton.layer.borderWidth = 1
            sureButton.layer.borderColor = Style.mainColor.cgColor
            sureButton.setTitle("次数不足，终止竞购", for: .normal)
            sureButton.setTitleColor(Style.mainColor, for: .normal)
        } else if s == 3 {
            // 竞购中断
            sureButton.backgroundColor = .white
            sureButton.layer.borderWidth = 1
            sureButton.layer.borderColor = Style.mainColor.cgColor
            sureButton.setTitle("保证金不足，终止竞购", for: .normal)
            sureButton.setTitleColor(Style.mainColor, for: .normal)
        } else if s == 4 {
            sureButton.backgroundColor = "#CCCCCC".zm.hex()
            sureButton.layer.borderWidth = 0
            sureButton.setTitle("自动竞购结束", for: .normal)
            sureButton.setTitleColor(.white, for: .normal)
        } else if s == 5 {
            sureButton.backgroundColor = "#CCCCCC".zm.hex()
            sureButton.layer.borderWidth = 0
            sureButton.setTitle("达到参与上限，终止竞购", for: .normal)
            sureButton.setTitleColor(.white, for: .normal)
        }
    }
    
    deinit {
        XMLogger.info("detail deinit")
    }
}
